<template>
    <div class="article-container">
        <!-- 返回按钮 -->
        <div class="back-btn" @click="goBack">
            <van-icon name="arrow-left" size="20" color="#333"/>
        </div>

        <!-- 收藏按钮 -->
        <div 
            class="collect-btn" 
            @click="toggleCollection"
            :style="{ left: position.x + 'px', top: position.y + 'px' }"
            @touchstart="startDrag"
            @touchmove="onDrag"
            @touchend="endDrag"
        >
            <van-icon :name="isCollected ? 'star' : 'star-o'" size="20" :color="isCollected ? 'yellow' : '#333'"/>
        </div>

        <!-- 文章内容 -->
        <div class="article-content" v-if="article">
            <h1 class="title">{{ article.title }}</h1>
            <div class="meta">
                <span class="time">{{ article.createTime }}</span>
            </div>
            <div class="cover-image" v-if="article.coverImg">
                <img :src="article.coverImg" :alt="article.title">
            </div>
            <div class="content" v-html="article.content"></div>
        </div>

        <!-- 加载状态 -->
        <div class="loading" v-else>
            <van-loading type="spinner" />
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getArticleDetail, toggleCollectionApi, checkCollectionApi } from '../api';
import { showToast, Icon } from 'vant';
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();

const route = useRoute();
const router = useRouter();
const article = ref(null);
const isCollected = ref(false);
const position = ref({
    x: window.innerWidth - 51, // 初始位置在右上角
    y: window.innerHeight - 100
});

let startPos = { x: 0, y: 0 };
let isDragging = false;

const startDrag = (e) => {
    startPos = {
        x: e.touches[0].clientX - position.value.x,
        y: e.touches[0].clientY - position.value.y
    };
    isDragging = true;
};

const onDrag = (e) => {
    if (!isDragging) return;
    
    const newX = e.touches[0].clientX - startPos.x;
    const newY = e.touches[0].clientY - startPos.y;
    
    // 限制按钮在屏幕范围内
    position.value = {
        x: Math.max(0, Math.min(newX, window.innerWidth - 36)),
        y: Math.max(0, Math.min(newY, window.innerHeight - 36))
    };
};

const endDrag = () => {
    isDragging = false;
};

// 获取文章详情
const getDetail = async () => {
    try {
        // 从路由参数中获取 id
        const id = route.params.id;
        const userId = userStore.userInfo.id;
        const res = await getArticleDetail(id,userId);
        if (res.data.code === 200) {
            article.value = res.data.data;
            
        } else {
            showToast('获取文章失败');
        }
    } catch (error) {
        console.error('获取文章详情失败：', error);
        showToast('获取文章失败');
    }
};

// 检查收藏状态  
const checkCollectionStatus = async () => {  
    // 未登录不检查收藏状态  
    if (!userStore.token) return;  

    try {  
        const id = route.params.id;  
        const res = await checkCollectionApi(id);  
        // 根据后端返回的布尔值设置收藏状态  
        if (res.data.code === 200) {  
            isCollected.value = res.data.data;  
        }  
    } catch (error) {  
        console.error('检查收藏状态失败：', error);  
    }  
};  

// 切换收藏状态  
const toggleCollection = async () => {  
    // 未登录提示登录  
    if (!userStore.token) {  
        showToast('请先登录');  
        return;  
    }  

    try {  
        const id = route.params.id;  
        const res = await toggleCollectionApi(id);  
        if (res.data.code === 200) {  
            // 切换收藏状态  
            isCollected.value = !isCollected.value;  
            // 根据当前收藏状态显示提示  
            showToast(isCollected.value ? '收藏成功' : '取消收藏');  
        } else {  
            showToast(res.data.message || '操作失败');  
        }  
    } catch (error) {  
        console.error('收藏/取消收藏失败：', error);  
        showToast('操作失败');  
    }  
}; 

// 返回上一页
const goBack = () => {
    router.back();
};

onMounted(() => {
    getDetail();
    checkCollectionStatus();
});
</script>

<style lang="scss" scoped>
.article-container {
    padding: 20px;
    min-height: 100vh;
    background: url('@/assets/images/articleBack.png') no-repeat center center;
    background-size: cover;
    position: relative;

    // 添加一个白色半透明遮罩，让内容更易读
    &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255, 255, 255, 0.9);
        z-index: 0;
    }

    // 让内容显示在遮罩层上面
    .back-btn {
        position: fixed;
        top: 15px;
        left: 15px;
        z-index: 11;
        width: 36px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 50%;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        cursor: pointer;

        &:active {
            background: rgba(245, 245, 245, 0.9);
        }
    }

    .collect-btn {
        position: fixed;
        z-index: 11;
        width: 36px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 50%;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        cursor: pointer;
        touch-action: none; // 防止触摸事件被系统处理
        user-select: none; // 防止文本被选中
        transition: transform 0.2s ease;

        &:active {
            background: rgba(245, 245, 245, 0.9);
            transform: scale(0.95);
        }
    }

    .article-content {
        position: relative;
        z-index: 1;
        .title {
            font-size: 24px;
            font-weight: bold;
            color: #333;
            margin-bottom: 16px;
            padding-top: 20px;
        }

        .meta {
            color: #999;
            font-size: 14px;
            margin-bottom: 20px;
        }

        .cover-image {
            margin-bottom: 20px;
            border-radius: 12px;
            overflow: hidden;

            img {
                width: 100%;
                height: auto;
                object-fit: cover;
            }
        }

        .content {
            font-size: 16px;
            line-height: 1.8;
            color: #333;

            ::v-deep(img) {
                max-width: 100%;
                height: auto;
                margin: 10px 0;
            }

            ::v-deep(p) {
                margin: 16px 0;
            }
        }
    }

    .loading {
        position: relative;
        z-index: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 200px;
    }
}
</style>    